package com.inmaytide.website.service.deploy.impl;

import com.inmaytide.website.domain.entities.deploy.DeployProject;
import com.inmaytide.website.framework.bean.JsonResult;
import com.inmaytide.website.mapper.deploy.DeployProjectMapper;
import com.inmaytide.website.service.deploy.DeployProjectService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;


@Service
public class DeployProjectServiceImpl implements DeployProjectService {

    @Resource
    private DeployProjectMapper mapper;

    @Override
    public List<DeployProject> findList() {
        return mapper.findList();
    }

    @Override
    public DeployProject findOne(Long id) {
        return mapper.findOne(id);
    }

    @Override
    public JsonResult save(DeployProject project) {
        // 校验
        if (!validDir(project.getPath()))
            return new JsonResult(false, "项目路径验证失败！");

        // 保存
        int successFlag = 0;
        project.setPath(new File(project.getPath()).getAbsolutePath());
        if (project.getId() == null) {
            successFlag = mapper.insert(project);
        } else {
            successFlag = mapper.updateByPrimaryKey(project);
        }

        // 返回
        if (successFlag == 1)
            return new JsonResult(true, "操作成功！");
        return new JsonResult(false, "操作失败！");
    }

    @Override
    public long getMaxSort() {
        return mapper.getMaxSort();
    }

    /**
     * 验证服务器文件夹
     *
     * @param path
     * @return
     */
    @Override
    public boolean validDir(String path) {
        if (StringUtils.isBlank(path)) {
            return false;
        }

        boolean valid = true;
        File remoteDir = new File(path);

        // 绝对路径验证
        if (!remoteDir.isAbsolute()) {
            valid = false;
        }

        // 存在验证
        if (!remoteDir.exists()) {
            valid = false;
        }

        // 文件夹验证
        if (remoteDir.isFile()) {
            valid = false;
        }
        // 返回
        return valid;
    }

    @Override
    public JsonResult delete(Long id) {
        if (id == null)
            return new JsonResult(false, "id不能为空！");

        int successFlag = mapper.deleteByPrimaryKey(id);
        if (successFlag == 0)
            return new JsonResult(false, "操作失败！");
        return new JsonResult(true, "操作成功！");
    }

    @Override
    public List<DeployProject> findProjectsInUse() {
        return mapper.findProjectsInUse();
    }

}
